package com.zc.controller;

import com.zc.entity.User;
import com.zc.entity.Userandteam;
import com.zc.entity.Userteam;
import com.zc.mapper.UserMapper;
import com.zc.mapper.UserandteamMapper;
import com.zc.mapper.UserteamMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class ItemController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserandteamMapper userandteamMapper;
    @Autowired
    UserteamMapper userteamMapper;
    @GetMapping("/team")
    public  String  getItem(HttpSession session,Model model)
    {
        int id =(int)session.getAttribute("userid");
        Userteam userteam =userteamMapper.selectByUserId(id);
        if(userteam==null)
        {

            return "team/teamadd";
        }else {
            logger.info(userteam.getNewdate().toString());
            model.addAttribute("userteam",userteam);
            return "team/team";
        }

    }
    @PostMapping("/team")
    public String addItem(Userteam userteam, HttpSession session, Map model)
    {
        userteam.setNewdate(new Date());
        userteam.setUserid((int)session.getAttribute("userid"));
        userteamMapper.insert(userteam);
        int id =(int)session.getAttribute("userid");
        Userandteam userandteam=new Userandteam();
        userandteam.setUserid(id);
        userandteam.setTeamid(userteamMapper.selectByUserId(id).getId());
        userandteamMapper.insert(userandteam);
        logger.info(userteam.getNewdate().toString());
        model.put("userteam",userteam);
        return "team/team";


    }
    @ResponseBody
    @GetMapping("/userandteam")
    public List<User> getUserAndTeam(HttpSession session)
    {

        int teamid=(int) session.getAttribute("teamid");


        return userMapper.selectByTeamId(teamid);
    }
    @ResponseBody
    @DeleteMapping("/userandteam/{id}")
    public void deleteUserAndTeam(@PathVariable("id") int id)
    {
        userandteamMapper.deleteByPrimaryKey(id);
    }
    @ResponseBody
    @PostMapping ("/userandteamadd/{id}")
    public  void  userandteamadd(@PathVariable("id") int id ,HttpSession session)
    {
        int teamid=(int) session.getAttribute("teamid");
        Userandteam userandteam=new Userandteam();
        userandteam.setUserid(id);
        userandteam.setTeamid(teamid);
        userandteamMapper.insert(userandteam);

    }
}
